package practice1_100;

import java.util.*;

public class Practice438 {
    public List<Integer> findAnagrams(String s, String p) {
        Map<Character,Integer> count= new HashMap<>();
        Map<Character,Integer> actual= new HashMap<>();
        List<Integer> list =new ArrayList<>();

        //统计p中元素个数
        for (int i=0;i<p.length();i++){
            addToMap(count,p.charAt(i));
        }

        //滑动窗口，两个指针left，right
        int left=0,right=0;
        while (right<s.length()){
            addToMap(actual,s.charAt(right));
            if(right-left+1==p.length()) {
                if (count.equals(actual)) {
                    list.add(left);
                }
                removeToMap(actual,s.charAt(left));
                left++;
            }
            right++;
        }
        return list;
    }


    //移入map的操作
    public void addToMap (Map<Character,Integer> map,Character character){
        if (!map.containsKey(character))
            map.put(character,1);
        else
            map.put(character,map.get(character)+1);
    }
    //移出map操作
    public void removeToMap (Map<Character,Integer> map,Character character){
        if (map.get(character)==1)
            map.remove(character);
        else
            map.put(character,map.get(character)-1);
    }


    public static void main(String[] args) {
        Practice438 practice438 =new Practice438();
        List list= practice438.findAnagrams("abab","ab");
        System.out.println(list);

    }
}
